package com.gitee.ixtf.mongo

import com.gitee.ixtf.core.AbstractUnitOfWork
import com.gitee.ixtf.core.IEntity
import com.gitee.ixtf.core.Jassert
import com.gitee.ixtf.mongo.Jmongo.Companion.idEq
import com.gitee.ixtf.mongo.kotlinx.exists
import com.mongodb.kotlin.client.coroutine.MongoCollection

class MongoUnitOfWork(private val jmongo: Jmongo) : AbstractUnitOfWork() {
  @Suppress("UNCHECKED_CAST")
  private fun collection(entity: IEntity) =
      jmongo.entityCollection(entity::class.java) as MongoCollection<Any>

  override suspend fun commit() {
    saveList.forEach { entity ->
      if (collection(entity).exists(entity.id)) registerDirty(entity) else registerNew(entity)
    }
    deleteList.forEach { entity ->
      entity.deleted = true
      registerDirty(entity)
    }
    newList.forEach { entity ->
      val result = collection(entity).insertOne(entity)
      Jassert.isTrue(result.wasAcknowledged()) { "insertOne[$entity]" }
    }
    dirtyList.forEach { entity ->
      val result = collection(entity).replaceOne(idEq(entity), entity)
      Jassert.isTrue(result.wasAcknowledged()) { "replaceOne[$entity]" }
    }
    purgeList.forEach { entity ->
      val result = collection(entity).deleteOne(idEq(entity))
      Jassert.isTrue(result.wasAcknowledged()) { "purgeOne[$entity]" }
    }
  }

  override suspend fun rollback() {
    TODO("Not yet implemented")
  }
}
